﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NetCoreCMS.Common;
using NetCoreCMS.Common.OAuth;
using NetCoreCMS.IServices;

namespace NetCoreCMS.Web.Controllers
{
    public class OauthController : Controller
    {
        public IWebHostEnvironment _env { get; set; }
        public IUser_oauth_appService _user_oauth_app{get;set;}
        public IActionResult Index()
        {
            string weburl = Common.XMLConfig.Sysconfig.loadConfig(_env.ContentRootPath).weburl;
            if (string.IsNullOrEmpty(weburl))
                weburl = Request.Scheme+"://"+Request.Host.Host.ToString();
            var config = _user_oauth_app.GetFirst(); //获取OAuth应用信息
            string state = Guid.NewGuid().ToString().Replace("-", "");
            HttpContext.Session.SetString("oauth_state",state); //防止CSRF攻击
            string send_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + config.oauth_app_id + "&redirect_uri=" + Utils.UrlEncode((weburl+config.return_uri).ToLower()) + "&response_type=code&scope=snsapi_userinfo&state=" + state + "#wechat_redirect";
            if (!string.IsNullOrEmpty(send_url))
            {
                return Redirect(send_url); //跳转到该网址
            }
            else
            {
                return Redirect("/Web/Error/Index?msg=" + Utils.UrlEncode("出错了，无法找到该OAuth应用接口！"));
            }
        }
        public IActionResult return_url()
        {
            if (HttpContext.Session.GetString("oauth_state") == null )
            {
                return Redirect("/Web/Error/Index?msg=" + Utils.UrlEncode("出错了，无法获取Session信息！"));
            }
            //取得返回参数
            string state = CMSRequest.GetQueryString("state",HttpContext);
            if (state != HttpContext.Session.GetString("oauth_state"))
            {
                return Redirect("/Web/Error/Index?msg=" + Utils.UrlEncode("出错了，state未初始化！"));
            }
            return weixin();
        }
        #region 微信登录处理方法===========================
        private IActionResult weixin()
        {
            string weburl = Common.XMLConfig.Sysconfig.loadConfig(_env.ContentRootPath).weburl;
            if (string.IsNullOrEmpty(weburl))
                weburl = Request.Scheme + "://" + Request.Host.Host.ToString();
            var config = _user_oauth_app.GetFirst();
            string access_token = string.Empty;
            string expires_in = string.Empty;
            string openid = string.Empty;
            //取得返回参数
            string state = CMSRequest.GetQueryString("state",HttpContext);
            string code = CMSRequest.GetQueryString("code", HttpContext);

            //第一步：获取Access Token
            Dictionary<string, object> dic = weixin_helper.get_access_token(config.oauth_app_id, config.oauth_app_key, (weburl+config.return_uri).ToLower(), code);
            if (dic == null || !dic.ContainsKey("access_token"))
            {
                return Redirect("/Web/Error/Index?msg=" + Utils.UrlEncode("出错了，无法获取Access Token，请检查App Key是否正确！"));
            }

            access_token = dic["access_token"].ToString();
            expires_in = dic["expires_in"].ToString();
            openid = dic["openid"].ToString();
            //储存获取数据用到的信息
            HttpContext.Session.SetString("oauth_name",config.oauth_name);
            HttpContext.Session.SetString("oauth_access_token",access_token);
            HttpContext.Session.SetString("oauth_openid",openid);
            var sub = weixin_helper.get_access_token(config.oauth_app_id, config.oauth_app_key)["access_token"];
            HttpContext.Session.SetString("sub_AccessToken", sub.ToString());
            //第二步：跳转到指定页面
            return Redirect("/Web/Login/Oauth_login");
        }
        #endregion
    }
}
